package com.hdax.dm.item.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hdax.dm.common.code.CodeEnum;
import com.hdax.dm.common.exception.DmException;
import com.hdax.dm.entity.item.ItemComment;
import com.hdax.dm.item.dto.ItemCommentDto;
import com.hdax.dm.item.feign.OrderFeign;
import com.hdax.dm.item.mappers.ItemCommentMapper;
import com.hdax.dm.item.service.ItemCommentService;
import com.hdax.dm.item.vo.ItemCommentVo;
import com.hdax.dm.utils.CommonResponse;
import com.hdax.dm.utils.ResponseUtil;
import com.hdax.dm.utils.Token;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class ItemCommentServiceImpl extends ServiceImpl<ItemCommentMapper, ItemComment> implements ItemCommentService {


    @Autowired
    private OrderFeign orderFeign;
    @Autowired
    private Token tokenUtil;
    @Override
    public CommonResponse getComments(Long itemId) {
        QueryWrapper<ItemComment> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("itemId",itemId);
        List<ItemComment> itemComments = this.list(queryWrapper);
        List<ItemCommentDto> itemCommentDtoList = new ArrayList<>();
        itemComments.forEach(itemComment->{
            ItemCommentDto itemCommentDto = new ItemCommentDto();
            BeanUtils.copyProperties(itemComment,itemCommentDto);
            //TODO:远程调用获取图片
            itemCommentDtoList.add(itemCommentDto);
        });

        return ResponseUtil.returnSuccess(itemCommentDtoList);
    }


    @Override
    public CommonResponse addComments(ItemCommentVo itemCommentVo,String token) throws DmException {
        Long userId = Long.parseLong(tokenUtil.token(token));
        if(userId == 0L){
            throw new DmException(CodeEnum.USER_ITEM_NOT_EXISTS);
        }
        //添加评论信息
        ItemComment itemComment = new ItemComment();
        BeanUtils.copyProperties(itemCommentVo,itemComment);
        //查询此用户是否买过该商品
        if (orderFeign.getCount(userId,itemComment.getItemId())<=0){
            //用户没用买过此商品无法进行评论
            throw new DmException(CodeEnum.USER_ITEM_NOT_EXISTS);
        }
        itemComment.setUserId(userId);
        itemComment.setContent(itemCommentVo.getComment());
        return ResponseUtil.returnSuccess(this.save(itemComment));
    }
}
